package com.sdx.console.saas.web;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Date;
import java.util.Collections;

import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.ibeetl.admin.core.file.FileService;
import com.sdx.common.entity.ResCloudFile;
import com.sdx.common.service.ResCloudFileService;
import com.sdx.common.utils.JacksonUtils;
import com.sdx.console.saas.entity.SaasTenant;
import com.sdx.console.saas.service.SaasTenantService;
import com.sdx.service.ConfigService;
import com.sdx.third.AliOSSApi;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.beetl.sql.core.engine.PageQuery;
import org.jxls.common.Context;
import org.jxls.reader.ReaderBuilder;
import org.jxls.reader.ReaderConfig;
import org.jxls.reader.XLSReadMessage;
import org.jxls.reader.XLSReadStatus;
import org.jxls.reader.XLSReader;
import org.jxls.util.JxlsHelper;
import org.mockito.internal.util.StringUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import com.ibeetl.admin.console.web.dto.DictExcelImportData;
import com.ibeetl.admin.console.web.query.UserQuery;
import com.ibeetl.admin.core.annotation.Function;
import com.ibeetl.admin.core.annotation.Query;
import com.ibeetl.admin.core.entity.CoreDict;
import com.ibeetl.admin.core.entity.CoreUser;
import com.ibeetl.admin.core.web.JsonResult;
import com.ibeetl.admin.core.web.JsonReturnCode;
import com.ibeetl.admin.core.util.*;
import com.sdx.common.utils.*;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import com.ibeetl.admin.core.web.AuthorizedBaesController;


/**
 * SaasTenant 接口
 */
@RequestMapping("/saas/saasTenant")
@Controller
public class SaasTenantController extends AuthorizedBaesController{
	private static final Logger log = LoggerFactory.getLogger(SaasTenantController.class);
    private static final String MODEL = "/saas/saasTenant";


    @Resource
	private SaasTenantService saasTenantService;


    @Resource
    private FileService fileService;

    @Resource
    private ResCloudFileService resCloudFileService;

	/**
	 * 初始化页面需要的列表数据，
	 *
	 */
	private void setPageParam(ModelAndView view,HttpServletRequest request) {
		List<Map<String,Object>> tenantTypeList = new ArrayList<>();
		Map<String,Object> map = new HashMap<>();
		map.put("id",1);
		map.put("name","普通机构");
		tenantTypeList.add(map);
		view.addObject("tenantTypeList",tenantTypeList);
	}

    /* 页面 */

    @GetMapping("/index.do")
    @Function("saas.saasTenant.query")
    @ResponseBody
    public ModelAndView index(HttpServletRequest request) {
        ModelAndView view = new ModelAndView(MODEL+"/index.html") ;
		setPageParam(view,request);
        return view;
    }

    @GetMapping("/edit.do")
    @Function("saas.saasTenant.edit")
    @ResponseBody
    public ModelAndView edit(HttpServletRequest request,Integer tenantId) {
        ModelAndView view = new ModelAndView(MODEL+"/add.html");
        SaasTenant saasTenant = saasTenantService.queryById(tenantId);
        view.addObject("saasTenant", saasTenant);

		setPageParam(view,request);
		try {
			view.addObject("saasTenantJson", JacksonUtils.toJsonString(saasTenant,JacksonUtils.DF1));
		} catch (JsonProcessingException e) {
			e.printStackTrace();
		}
        return view;
    }

    @GetMapping("/add.do")
    @Function("saas.saasTenant.add")
    @ResponseBody
    public ModelAndView add(HttpServletRequest request) {
        ModelAndView view = new ModelAndView(MODEL+"/add.html");
		setPageParam(view,request);
        return view;
    }

    /* ajax json */

    @PostMapping("/list.json")
    @Function("saas.saasTenant.query")
    @ResponseBody
    public JsonResult<PageQuery> list(SaasTenant condtion)
    {
        PageQuery page = condtion.getPageQuery();
        saasTenantService.queryByCondition(page);
        return JsonResult.success(page);
    }

    private JsonResult save(boolean isNew,SaasTenant saasTenant,HttpServletRequest request
	) {
    	JsonResult result = JsonResult.success();
		String dir = DateUtil.now("yyyyMMdd");
    	String subPath = "/images/cover/"+dir+"/";
		String bucketName = "sdxcomm";
		CoreUser user = getLoginUser(request);

    	if (isNew) {
			saasTenant.setCreatedBy(user.getId().intValue());
			saasTenant.setCreatedName(user.getName());
			saasTenant.setCreatedTime(new Date());
			saasTenant.setUpdatedBy(user.getId().intValue());
			saasTenant.setUpdatedName(user.getName());
			saasTenant.setUpdatedTime(new Date());
			saasTenantService.save(saasTenant);
		} else {
			saasTenant.setUpdatedBy(user.getId().intValue());
			saasTenant.setUpdatedName(user.getName());
			saasTenant.setUpdatedTime(new Date());
			saasTenantService.updateTemplate(saasTenant);
		}
		return result;
	}
    @PostMapping("/add.json")
    @Function("saas.saasTenant.add")
    @ResponseBody
    public JsonResult add(@Validated(ValidateConfig.ADD.class)SaasTenant saasTenant,HttpServletRequest request
		)
    {

        return save(true,saasTenant,request
		);
    }

    @PostMapping("/update.json")
    @Function("saas.saasTenant.edit")
    @ResponseBody
    public JsonResult<String> update(@Validated(ValidateConfig.UPDATE.class)  SaasTenant saasTenant,HttpServletRequest request
		) {
		return save(false,saasTenant,request
		);
    }


   
    @GetMapping("/view.json")
    @Function("saas.saasTenant.query")
    @ResponseBody
    public JsonResult<SaasTenant>queryInfo(Integer tenantId) {
        SaasTenant saasTenant = saasTenantService.queryById( tenantId);
        return  JsonResult.success(saasTenant);
    }

    @PostMapping("/delete.json")
    @Function("saas.saasTenant.del")
    @ResponseBody
    public JsonResult delete(String ids) {
		List<String> idList = Utils.strToList(ids,",");
        saasTenantService.batchDelSaasTenant(idList);
        return JsonResult.success();
    }


    @GetMapping("/info.do")
    @Function("saas.saasTenant.info")
    @ResponseBody
    public ModelAndView info(HttpServletRequest request) {
        ModelAndView view = new ModelAndView(MODEL+"/info.html");
        CoreUser user = getLoginUser(request);
        SaasTenant saasTenant = saasTenantService.queryById(user.getTenantId());
        String picture = saasTenant.getPicture();
        if(StringUtils.isNotEmpty(picture)){
            JSONArray array  = JSON.parseArray(picture);
            StringBuffer sb = new StringBuffer();
            for (Object o : array) {
                JSONObject json = (JSONObject)o;
                sb.append(json.get("name")).append("#").append(json.get("no")).append("#").append(json.get("url")).append("@");
            }
            sb.deleteCharAt(sb.length()-1);
            saasTenant.setPictureJson(sb.toString());
        }
        view.addObject("saasTenant", saasTenant);
        setPageParam(view,request);
        try {
            view.addObject("saasTenantJson", JacksonUtils.toJsonString(saasTenant,JacksonUtils.DF1));
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return view;
    }


    @PostMapping("/info.json")
    @Function("saas.saasTenant.info")
    @ResponseBody
    public JsonResult infoSave(@Validated(ValidateConfig.ADD.class)SaasTenant saasTenant,HttpServletRequest request
            ,@RequestParam("logoFile") MultipartFile logoFile) {
        JsonResult result = JsonResult.success();
        String dir = DateUtil.now("yyyyMMdd");
        String subPath = "/images/sass/"+dir+"/";
        String bucketName = "sdxcomm";
        CoreUser user = getLoginUser(request);
        if (!FileUtils.isEmptyFile(logoFile)) {
            try{
                String mainImgFileNamePair = FileUtils.upload(subPath,logoFile);
                String mainImgStoreFile = mainImgFileNamePair.split("::")[0];
                mainImgStoreFile = subPath+mainImgStoreFile;
                AliOSSApi.uploadLocalFile(FileUtils.getRoot()+mainImgStoreFile,bucketName,mainImgStoreFile.substring(1));
                String mainImgUrl = "https://sdxcomm."+ ConfigService.ossDomain+mainImgStoreFile;
                saasTenant.setLogo(mainImgUrl);
                resCloudFileService.insertResFile(ResCloudFile.ALI,mainImgStoreFile,mainImgUrl,"a","logo");
            }catch(Exception e) {
                e.printStackTrace();
                result.setCode(JsonReturnCode.IO_ERROR.getCode());
                result.setMsg(e.getMessage());
            }
        }
        String pictureJson = saasTenant.getPictureJson();
        JSONArray array = new JSONArray();
        if(StringUtils.isNotEmpty(pictureJson)){
            String[] split = pictureJson.split("@");
            for (String s : split) {
                String[] s1 = s.split("#");
                JSONObject json = new JSONObject();
                json.put("url",s1[2]);
                json.put("name",s1[0]);
                json.put("no",s1[1]);
                array.add(json);
            }
        }
        if(array.size()>0){
            saasTenant.setPicture(array.toJSONString());
        }else{
            saasTenant.setPicture(" ");
        }
        saasTenant.setUpdatedBy(user.getId().intValue());
        saasTenant.setUpdatedName(user.getName());
        saasTenant.setUpdatedTime(new Date());
        saasTenantService.updateTemplate(saasTenant);
        return result;
    }

    /**
     *  图片上传
     * @param file
     * @return
     */
    @RequestMapping("/upload.json")
    @ResponseBody
    public JSONObject uploadImg(MultipartFile file) {
        JSONObject jsobject = new JSONObject();
        String dir = DateUtil.now("yyyyMMdd");
        String subPath = "/images/saas/"+dir+"/";
        String bucketName = "sdxcomm";
        if (!FileUtils.isEmptyFile(file)) {
            try
            {

                String originalFilename = file.getOriginalFilename();
                originalFilename = originalFilename.substring(0,originalFilename.indexOf("."));
                String[] name =originalFilename.split("_");
                String fileNamePair = FileUtils.upload(subPath,file);
                String storeFile = fileNamePair.split("::")[0];
                storeFile = subPath+storeFile;
                AliOSSApi.uploadLocalFile(FileUtils.getRoot()+storeFile,bucketName,storeFile.substring(1));
                String url = "https://sdxcomm."+ ConfigService.ossDomain+storeFile;
                jsobject.put("url",url);
                jsobject.put("name",name[0]);
                jsobject.put("no",name[1]);
                jsobject.put("state", "SUCCESS");
                jsobject.put("title", "");
                jsobject.put("original", "");
                resCloudFileService.insertResFile(ResCloudFile.ALI,storeFile,url,"a","logo");
            }catch(Exception e) {
                e.printStackTrace();
                jsobject.put("state", "FAIL");
                jsobject.put("title", "");
                jsobject.put("original", "");
                jsobject.put("url","");
            }
        }
        return jsobject;
    }

}
